

import commands
import apt_pkg

from aptsources import distro



def find_pkg_by_file(fname):

    #status, output = commands.getstatusoutput("apt-file find " + fname)
    status, output = commands.getstatusoutput("dpkg -S " + fname)
    
    if status != 0:
        return None
    
    return output.split(":")[0]


def download_pkgs(pkgs):
    """Donwload the pkgs in formart ["pkgname"...]."""
    for pkg in pkgs:
        status,output = commands.getstatusoutput("sudo apt-get install --reinstall -d "
                                             + pkg)
        if status != 0:
            raise Exception("downloading apk file failed:", output)


def download_pkg(pkg):
    return download_pkgs([pkg])


def _conver_deb_special_char(deb):
    """
    http://www.cyberciti.biz/faq/linuxunix-rules-for-naming-file-and-directory-names/
    """
    deb = deb.replace(r':', '%'+'%x'%ord(':') )
    deb = deb.replace(r'|', '%'+'%x'%ord('|') )
    deb = deb.replace(r'&', '%'+'%x'%ord('&') )
    deb = deb.replace(r'>', '%'+'%x'%ord('>') )
    return deb


def get_cached_deb_fname(pkg):
    """
    Architecture: all
    Source: ibus-pinyin
    Version: 1.4.0-1
    
    """
    
    APT_CACHE = "/var/cache/apt/archives/"
    
    version_cmd = "apt-cache show  %s | grep Version | head -1 "%pkg
    arch_cmd = "apt-cache show  %s | grep Architecture | head -1"%pkg

    
    status,version = commands.getstatusoutput(version_cmd)
    status,arch = commands.getstatusoutput(arch_cmd)

    deb = APT_CACHE + pkg + "_" + version.split(":",1)[1].strip() + "_" \
                + arch.split(":")[1].strip() + ".deb"


    return _conver_deb_special_char(deb)


def unpack_deb(deb, fname=''):
    
    status,output = commands.getstatusoutput("mkdir -p /tmp/_cfc_")
    if status != 0:
            raise Exception(("unpack_deb deb file failed:%s"%output))
    
    status,output = commands.getstatusoutput("dpkg-deb --fsys-tarfile " + deb
                                                + " | sudo tar xvf - " + " -C /tmp/_cfc_")

    if status != 0:
            raise Exception(("unpack_deb deb file failed:%s"%output))


def calc_md5(fname):
    status,output = commands.getstatusoutput("md5sum " + fname)
    
    if status != 0:
            raise Exception(("md5sum a file failed:%s"%output))

    return output.split(" ")[0]
    
def calc_tmp_file_md5(fname):
    """Unpack deb will show in /tmp/_cfc_..."""
    return calc_md5("/tmp/_cfc_"+fname)

